package me.zhengjie.modules.lock.service.impl;

import com.zelk.lock.api.clent.feign.LockDevicePwdApi;
import com.zelk.lock.api.dto.LockDevicePwdListDTO;
import com.zelk.lock.api.dto.LockOfflinePwdResultDTO;
import com.zelk.lock.api.vo.LockDevicePwdPageVO;
import com.zelk.lock.api.vo.LockOfflinePwdVO;
import com.zelk.smartlock.common.response.ResponsePage;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.lock.mapping.MappingUtil;
import me.zhengjie.modules.lock.service.LockDevicePwdService;
import me.zhengjie.modules.lock.service.dto.LockDeviceOfflinePwdDTO;
import me.zhengjie.modules.lock.service.vo.LockDeviceOfflinePwdVO;
import me.zhengjie.modules.lock.service.vo.LockDevicePwdListReqVO;
import me.zhengjie.modules.lock.util.RequestCall;
import me.zhengjie.utils.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class LockDevicePwdServiceImpl implements LockDevicePwdService {
    @Resource
    private LockDevicePwdApi lockDevicePwdApi;

    @Autowired
    private MappingUtil mappingUtil;

    @Override
    public Map<String, Object> getPwdList(LockDevicePwdListReqVO pwdListReqVO, Pageable pageable) {
        LockDevicePwdPageVO lockDevicePwdPageVO = mappingUtil.toLockDevicePwdPageVO(pwdListReqVO);
        lockDevicePwdPageVO.setPageIdx((long) pageable.getPageNumber());
        lockDevicePwdPageVO.setPageSize(pageable.getPageSize() <= 0 ? 50L : (long) pageable.getPageSize());
        ResponsePage<List<LockDevicePwdListDTO>> lockDevicePwdList = RequestCall.executePage(lockDevicePwdApi::getLockDevicePwdList, lockDevicePwdPageVO, null);
        List<LockDevicePwdListDTO> pwdListDTOS = Optional.ofNullable(lockDevicePwdList.getData()).orElse(new ArrayList<>());
        List<LockDevicePwdListDTO> deviceInfoListDTOS = pwdListDTOS.stream().map(v -> {
            LockDevicePwdListDTO pwdListDTO = mappingUtil.toLockDevicePwdListDTO(v);
            //TODO 还要填充商户名称
            return pwdListDTO;
        }).collect(Collectors.toList());
        return PageUtil.toPage(deviceInfoListDTOS, Objects.nonNull(lockDevicePwdList.getTotal()) ? lockDevicePwdList.getTotal() : 0);
    }

    @Override
    public LockDeviceOfflinePwdDTO getOfflinePwd(LockDeviceOfflinePwdVO offlinePwdVO) {
        LockOfflinePwdVO lockOfflinePwdVO = mappingUtil.toLockOfflinePwdVO(offlinePwdVO);
        LockOfflinePwdResultDTO lockOfflinePwdDTO = RequestCall.execute(lockDevicePwdApi::getOfflinePwd, lockOfflinePwdVO, null);
        LockDeviceOfflinePwdDTO offlinePwdDTO = mappingUtil.toLockDeviceOfflinePwdDTO(lockOfflinePwdDTO);
        return offlinePwdDTO;
    }
}
